package com.zzzy.config;


import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
@Order(-1)
public class DataSourceProxy {

    private Logger logger = Logger.getLogger(DataSourceProxy.class);

    //改变数据源
    @Before("@annotation(DataSource)")
    public void changeDataSource(JoinPoint joinPoint) {
        String dbid = "";//dataSource.name();

//        Object[] args = joinPoint.getArgs();
//        for (int i = 0; i < args.length; i++) {
//            System.out.println("第" + (i+1) + "个参数为:" + args[i]);
//        }
//        dbid = args[0].toString();

        dbid = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().getAttribute("tenent").toString();


        if (!DataSourceContextHolder.isContainsDataSource(dbid)) {
            //joinPoint.getSignature() ：获取连接点的方法签名对象
            logger.error("数据源 " + dbid + " 不存在使用默认的数据源 -> " + joinPoint.getSignature());
        } else {
            logger.debug("使用数据源：" + dbid);
            DataSourceContextHolder.setDataSourceType(dbid);
        }
    }

    @After("@annotation(DataSource)")
    public void clearDataSource(JoinPoint joinPoint) {
        //logger.debug("清除数据源 " + dataSource.name() + " !");
        DataSourceContextHolder.clearDataSourceType();
    }
}

